//
//  CZChoosePictureView.swift
//  git
//
//  Created by 徐 鹏超 on 16/4/15.
//  Copyright © 2016年 徐 鹏飞. All rights reserved.
//

import UIKit


// 不继承自 NSObjectProtocol delegate不能用weak
protocol CZChoosePictureViewCellDelegate: NSObjectProtocol{
    
    func didDeleteImage(index: Int)
    
}

let CZChoosePictrueItemMargin: CGFloat = 5

let CZChoosePictrueItemWH = (kUIScreenWidth - 2 * CZChoosePictureViewMargin - 2*CZChoosePictrueItemMargin)/3

let CZChoosePictureViewReuseIdentifier = "CZChoosePictureViewReuseIdentifier"




private let reuseIdentifier = "Cell"

class CZChoosePictureView: UICollectionView , UICollectionViewDataSource,UICollectionViewDelegate ,CZChoosePictureViewCellDelegate {
    
    // 在哪里调用,就在哪里声明
    var closure: (()->())?
    
    // 定义一个数组,来盛放图片
    private lazy var images: [UIImage] = [UIImage]()

    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    
    // 对外提供一个接口
    func addImage(image: UIImage){
        
        images.append(image)
        
        // 刷新数据
        reloadData()
        
    }
    
    
    // 如何才能知道有循环引用,看deinit有没有销毁
    deinit{
        printLog(" CZChoosePictureView 88")
    }
    
    private func setupUI(){
        
        dataSource = self
        
        delegate = self
        
        // 注册cell
        registerClass(CZChoosePictureViewCell.self, forCellWithReuseIdentifier: CZChoosePictureViewReuseIdentifier)
        
        //
        flowLayout.itemSize = CGSizeMake(CZChoosePictrueItemWH, CZChoosePictrueItemWH)
        flowLayout.minimumInteritemSpacing = CZChoosePictrueItemMargin
        flowLayout.minimumLineSpacing = CZChoosePictrueItemMargin
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    


    
}

extension CZChoosePictureView{
    
    
    
    
    /*
    加号什么时候有? 什么时候没有?
    0个图片的时候,没有加号
    1-8张图片的时候,有加号
    9张图片的时候,就没有了
    */
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 0 {
            return 0
        } else if images.count == 9 {
            return images.count
        } else {
            
            return images.count + 1
            
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        // 获取重用cell的时候,想到2步, 第一步: 注册cell,第二步: 重用的这里
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZChoosePictureViewReuseIdentifier, forIndexPath: indexPath) as! CZChoosePictureViewCell
        
        //        cell.backgroundColor = RandomColor()
        
        /*
        返回了 2个 item
        实际上 images 就有 1个
        
        indexPaht.item = 0
        indexPath.item = 1
        
        0 >= 1
        1 >= 1
        */
        if indexPath.item >= images.count {
            cell.image = nil
        } else {
            
            cell.image = images[indexPath.item]
        }
        
        
        cell.delegate = self
        
        cell.index = indexPath
        
        return cell
        
}
    
    func didDeleteImage(index: Int) {
        // 删除对应的图片
        images.removeAtIndex(index)
        
        reloadData()
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 指定点击了哪个
        // 怎么知道点击了最后一个
        if indexPath.item == images.count {
            
            // 闭包就是 调用的时候 执行
            closure?()
            
        }
    }

}
    class CZChoosePictureViewCell: UICollectionViewCell {
        
        // 需要把 CZChoosePictureView的索引 传递给 Cell
        // collectionView 对cell 有一个应用
        
        var index: NSIndexPath?
        
        weak var delegate: CZChoosePictureViewCellDelegate?
        
        var image: UIImage?{
            
            didSet{
                
                if image == nil { //应该显示加号,而且 不能显示删除按钮
                    
                    iconImageView.image = UIImage(named: "compose_pic_add_highlighted")
                    deleteButton.hidden = true
                    
                } else {
                    
                    iconImageView.image = image
                    
                    deleteButton.hidden = false
                }
            }
            
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            
            setupUI()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        
        private func setupUI(){
            
            addSubview(iconImageView)
            addSubview(deleteButton)
            // img 设置frame
            iconImageView.frame = self.bounds
            
            
            deleteButton.snp_makeConstraints { (make) -> Void in
                make.top.equalTo(self.snp_top)
                make.right.equalTo(self.snp_right)
            }
            
        }
        
        
        @objc private func deleteImage(){
            
            printLog("删除")
            // controller 删除数据
            delegate?.didDeleteImage(index!.item)
        }
        
        //MARK:--懒加载
        private lazy var iconImageView : UIImageView = {
            
            let img = UIImageView()
            
            return img
        }()
        
        
        //
        private lazy var deleteButton: UIButton = {
            
            let button = UIButton(type: UIButtonType.Custom)
            
            button.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
            
            button.sizeToFit()
            
            // 添加事件
            button.addTarget(self, action: "deleteImage", forControlEvents: UIControlEvents.TouchUpInside)
            
            return button
        }()
}
